import tkinter as tk
import player
import recorder
import time
import win32api
import win32gui
import win32con
import os

source_mainstream = "rtsp://192.168.0.123:554/live/mainstream"

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("SCM Demo")
        # 设置窗口初始宽度和高度
        window_width = 1600
        window_height = 910
        # 获取屏幕的宽度和高度
        screen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()
        # 计算窗口左上角的坐标，使其居中显示
        x = (screen_width - window_width) // 2
        y = (screen_height - window_height) // 2
        # 设置窗口的位置和大小
        self.geometry(f"{window_width}x{window_height}+{x}+{y}")

        self.left_frame = tk.Frame(self)
        self.right_frame = tk.Frame(self)

        # 使用 grid 布局
        self.left_frame.grid(row=0, column=0, sticky="nsew")
        self.right_frame.grid(row=0, column=1, sticky="nsew")
        # 设置列权重
        self.grid_columnconfigure(0, weight=7)
        self.grid_columnconfigure(1, weight=3)

        
        self.player = player.Player()
        self.recoder = recorder.Recorder()

        self.create_video_view()
        self.create_control_view()
        self.bind("<Configure>", self.on_resize)
        self.player.play(source_mainstream)
        # 添加标志位，用于记录上一次窗口大小
        self.last_width = 0
        self.last_height = 0
        # 初始化全屏标志
        self.is_fullscreen = False
        # 保存 right_frame 的原始 grid 信息
        self.right_frame_grid_info = self.right_frame.grid_info()
        # 获取屏幕尺寸
        self.screen_width = screen_width
        self.screen_height = screen_height
       
        # 初始化字幕
        self.player.set_marquee()
        # 启动时间更新
        self.update_time()

        self.is_recording = False  # 新增录制状态标志        


    def create_video_view(self):
        self._canvas = tk.Canvas(self.left_frame, bg="black")
        self._canvas.pack(fill=tk.BOTH, expand=True)
        self.player.set_window(self._canvas.winfo_id())

    def create_control_view(self):
        tk.Button(self.right_frame, text="播放", command=lambda: self.click(0)).pack(pady=5)
        # 保存暂停按钮的引用
        self.pause_button = tk.Button(self.right_frame, text="暂停", command=lambda: self.click(1))
        self.pause_button.pack(pady=5)
        tk.Button(self.right_frame, text="停止", command=lambda: self.click(2)).pack(pady=5)
        # 新增全屏按钮
        tk.Button(self.right_frame, text="全屏", command=self.toggle_fullscreen).pack(pady=5)
        # 新增截图按钮
        tk.Button(self.right_frame, text="截图", command=self.take_screenshot).pack(pady=5)
        # 新增录制按钮
        self.record_button = tk.Button(self.right_frame, text="录制视频", command=self.toggle_recording)
        self.record_button.pack(pady=5)
        # 绑定 Esc 键事件
        self.bind("<Escape>", self.cancel_fullscreen)

    def toggle_recording(self):
        if not self.is_recording:
            self.start_recording()
        else:
            self.stop_recording()

    def start_recording(self):
        if not os.path.exists('data'):
            os.makedirs('data')
        timestamp = time.strftime("%Y%m%d-%H%M%S")
        recording_path = os.path.join('data', f"recording_{timestamp}.mp4")
        
        # self.recoder.start(source_mainstream, recording_path)
        self.player.start_recording(recording_path)

        self.is_recording = True
        self.record_button.config(text="停止录制")

    def stop_recording(self):
        # self.recoder.stop()
        self.player.stop_recording()

        self.is_recording = False
        self.record_button.config(text="录制视频")

    def click(self, action):
        if action == 0:
            if self.player.get_state() == 0:
                self.player.resume()
                if self.pause_button:
                    self.pause_button.config(text="暂停")
            elif self.player.get_state() == 1:
                pass
            else:
                self.player.play(source_mainstream)
                if self.pause_button:
                    self.pause_button.config(text="暂停")
        elif action == 1:
            if self.player.get_state() == 1:
                self.player.pause()
                if self.pause_button:
                    self.pause_button.config(text="恢复")
            else:
                self.player.resume()
                if self.pause_button:
                    self.pause_button.config(text="暂停")
        else:
            self.player.stop()
            if self.pause_button:
                self.pause_button.config(text="暂停")

    def take_screenshot(self):
        timestamp = time.strftime("%Y%m%d-%H%M%S")
        # 确保 data 文件夹存在
        if not os.path.exists('data'):
            os.makedirs('data')
        screenshot_path = os.path.join('data', f"screenshot_{timestamp}.png")
        self.player.take_screenshot(screenshot_path)

    def on_resize(self, event):
        # 检查触发事件的 widget 是否为主窗口
        if event.widget == self:
            # 检查窗口大小是否真的改变
            if event.width != self.last_width or event.height != self.last_height:
                # 计算 right_frame 宽度，至少占 30% 或者 300 像素
                right_width = max(300, int(event.width * 0.3))
                left_width = event.width - right_width

                # 不再需要手动设置宽度
                # self.left_frame.config(width=left_width)
                # self.right_frame.config(width=right_width)
                # 更新 Canvas 宽度和高度
                self._canvas.config(width=left_width, height=event.height)
                print(f"窗口宽度: {event.width}, 窗口高度: {event.height}")
                print(f"LEFT宽度: {left_width}, RIGHT宽度: {right_width}")
                # 更新标志位
                self.last_width = event.width
                self.last_height = event.height

    def toggle_fullscreen(self):
        if not self.is_fullscreen:
            # 保存当前窗口状态
            self.last_geometry = self.geometry()
            # 隐藏 right_frame
            self.right_frame.grid_forget()
            # 让 left_frame 占据整个窗口
            self.left_frame.grid(row=0, column=0, columnspan=2, sticky="nsew")

            # 获取当前窗口的位置和大小
            x = self.winfo_x()
            y = self.winfo_y()
            # 获取窗口所在的显示器
            hwnd = win32gui.FindWindow(None, self.title())
            monitor = win32api.MonitorFromPoint((x, y), win32con.MONITOR_DEFAULTTONEAREST)
            monitor_info = win32api.GetMonitorInfo(monitor)
            screen_rect = monitor_info['Monitor']
            screen_width = screen_rect[2] - screen_rect[0]
            screen_height = screen_rect[3] - screen_rect[0]

            # 设置窗口为全屏
            self.attributes('-fullscreen', True)
            # 更新 Canvas 大小为所在屏幕尺寸
            self._canvas.config(width=screen_width, height=screen_height)
            self.is_fullscreen = True
        else:
            self.cancel_fullscreen()

    def cancel_fullscreen(self, event=None):
        if self.is_fullscreen:
            # 恢复窗口状态
            self.attributes('-fullscreen', False)
            self.geometry(self.last_geometry)
            # 恢复 right_frame 的显示
            self.right_frame.grid(**self.right_frame_grid_info)
            # 恢复 left_frame 的布局
            self.left_frame.grid(row=0, column=0, columnspan=1, sticky="nsew")
            # 更新 Canvas 大小
            self._canvas.config(width=self.left_frame.winfo_width(), height=self.winfo_height())
            self.is_fullscreen = False

    def update_time(self):
        current_time = time.strftime("%Y-%m-%d %H:%M:%S")
        self.player.update_text(current_time)
        # 每秒刷新一次
        self.after(1000, self.update_time)

if "__main__" == __name__:
    app = App()
    app.mainloop()
